{% extends 'base.html'%}
{% block content %}
{# 使用length过滤器获取movies的长度 #}
<h6>一共有 {{ movies|length }} 部电影:</h6>
<form class="mb-3 col-md-8" method="post">
  <div class="row">
    <div class="col">
      <input id="title" type="text" class="form-control" placeholder="输入影片名称" name="title">
    </div>
    <div class="col">
      <input id="year" class="form-control" placeholder="输入上映年份" name="year">
    </div>
    <div class="col">
      <button type="submit" class="btn btn-dark">新增</button>
    </div>

  </div>
</form>
<ul class="list-group">
    {% for movie in movies: %}
    <li class="list-group-item d-flex justify-content-between align-items-center">
        {{ movie.title }} - {{movie.year}}
        <span class="badge bg-warning ms-2"><a target="_blank" href="https://movie.douban.com/subject_search?search_text={{ movie.title }}">豆瓣</a></span>
        <div class="ms-auto">
           <a class="btn btn-sm btn-danger float-end" href="{{ url_for('delete', movie_id = movie.id) }}" role="button" onclick="alert('确认删除该影片信息么？')">删除</a>
           <a class="btn btn-sm btn-warning float-end  me-2" href="javascript:void(0)" role="button" onclick="loadMovieData({{ movie.id }})" data-bs-toggle="modal" data-bs-target="#editMovie">编辑</a>
        </div>
    </li>
    {% endfor %}
</ul>
<!-- 模态 -->
<div class="modal fade " id="editMovie">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <!-- 模态标题 -->
      <div class="modal-header">
        <h4 class="modal-title">编辑影片信息</h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <!-- 模态主体 -->
      <div class="modal-body">
        <form action="{{ url_for('do_update') }}" method="post">
          <input type="hidden" id="movie_id" name="movieID">
          <div class="mb-3 mt-3">
            <label for="new_title" class="form-label">影片名称：</label>
            <input type="text" class="form-control" id="new_title" name="newTitle">
          </div>
          <div class="mb-3">
            <label for="new_year" class="form-label">密码：</label>
            <input type="text" class="form-control" id="new_year"  name="newYear">
          </div>
          <div class="mt-5">
            <button type="submit" class="btn btn-primary">提交</button>
            <button type="button" class="btn btn-danger" data-bs-dismiss="modal">关闭</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
<script>
function loadMovieData(movieId) {
  // 使用 AJAX 请求从后台获取电影数据
  fetch(`/movie/update/${movieId}`)
    .then(response => response.json())
    .then(data => {
      // 填充数据到模态框中的表单
      document.getElementById('movie_id').value = data.id;
      document.getElementById('new_title').value = data.title;
      document.getElementById('new_year').value = data.year;
    })
    .catch(error => {
      console.error('未找到待修改的数据:', error);
    });
}
</script>
{% endblock %}
